﻿#include "fetchview.h"
#include "ui_fetchview.h"

FetchView::FetchView(QWidget *parent,
                     const QString &label,
                     const QString &detail) :
    BaseEditorDialog(parent),_label(label),_detail(detail),
    ui(new Ui::FetchView)
{
    ui->setupUi(this);

    table=T_RES_LOCATION;   //本地列表
    linkTable=T_RES_LINK;   //更新时间
    fetchTable=T_RES_FETCH; //下载列表

    fetchModel=new QStringListModel(this);
    ui->fetchView->setModel(fetchModel);
    ui->fetchView->setEditTriggers(QListView::NoEditTriggers);

    provider=new SimpleProvider(this);
    connect(provider,&SimpleProvider::received,
            this,&FetchView::onReceived);

    updateLocalLocation();
    updateFetchView();
    checkSyncTime();
    createMenu();
}

FetchView::~FetchView()
{
    delete ui;
}

void FetchView::checkSyncTime()
{
    QSqlQuery query;
    query.exec(QString("select addition from %1 where category='Entry' AND label='%2'")
               .arg(linkTable)
               .arg(_label));
    if(query.next())
    {
        QString last=query.value(0).toString();
        if(last.isEmpty())
        {
            do_sync();
            return;
        }
        lastSyncTime=QDateTime::fromString(last,DATETIME_FORMAT);
        if(!lastSyncTime.isValid())
        {
            do_sync();
            return;
        }

        qint64 offset=lastSyncTime.secsTo(QDateTime::currentDateTime());
        if(offset >= THRESHOLD_VALUE)
            do_sync();
    }
}

void FetchView::generateMenu()
{
    // menu->addAction(QStringLiteral("搜索..."),this,&FetchView::search);
    // menu->addSeparator();
    menu->addAction(QStringLiteral("更新下载源"),this,&FetchView::sync);
}

bool FetchView::addFetchItem(const QString &label,
                        const QString &detail)
{
    QSqlQuery query;
    query.prepare(QString("insert into %1 (category,label,detail) values (?,?,?)")
                  .arg(fetchTable));
    query.addBindValue(_label);
    query.addBindValue(label);
    query.addBindValue(detail);
    if(query.exec())
        return true;
    else
    {
        qDebug() << query.lastError().text();
        return false;
    }
}

void FetchView::onReceived(const QByteArray &data)
{
    QJsonDocument doc=QJsonDocument::fromJson(data);
    if(doc.isEmpty() || !doc.isObject())
        return;

    QJsonArray array=doc.object().value("detail").toArray();
    if(array.isEmpty())
        return;

    QStringList remoteList;
    QMap<QString,QString> remoteDetails;

    for(int i=0;i < array.size();i++)
    {
        QJsonObject obj=array.at(i).toObject();
        QString label=obj.value("label").toString();
        QString detail=obj.value("detail").toString();
        remoteList.append(label);
        remoteDetails.insert(label,detail);
    }

    if(fetchList == remoteList)
        return;

    int gap=remoteList.size() - fetchList.size();
    int i=0;
    for(QString label: remoteList) {
        if(!fetchList.contains(label))
        {
            fetchList.append(label);
            QString detail=remoteDetails.value(label);
            fetchDetails.insert(label,detail);
            if(addFetchItem(label,detail))
                i+=1;
        }
    }
    updateSyncTime();
    if(i=gap-1)
        fetchModel->setStringList(fetchList);
}

void FetchView::updateSyncTime()
{
    lastSyncTime=QDateTime::currentDateTime();
    QSqlQuery query;
    query.exec(QString("update %1 set addition='%2' where category='Entry' AND label='%3'")
               .arg(linkTable).arg(Today).arg(_label));
}

void FetchView::updateLocalLocation()
{
    if(!localList.isEmpty())
        localList.clear();

    QSqlQuery query;
    query.exec(QString("select label from %1 where category='%2'")
               .arg(table)
               .arg(_label));
    while (query.next()) {
        QString label=query.value(0).toString();
        localList.append(label);
    }
}

void FetchView::updateFetchView()
{
    if(!fetchList.isEmpty())
        fetchList.clear();
    if(!fetchDetails.isEmpty())
        fetchDetails.clear();

    QSqlQuery query;
    query.exec(QString("select label,detail from %1 where category='%2'")
               .arg(fetchTable)
               .arg(_label));
    while (query.next()) {
        QString label=query.value(0).toString();
        QString detail=query.value(1).toString();
        fetchList.append(label);
        fetchDetails.insert(label,detail);
    }

    fetchModel->setStringList(fetchList);
}

void FetchView::sync()
{
    if(lastSyncTime.secsTo(QDateTime::currentDateTime()) < 60)
        return;

    do_sync();
}

void FetchView::do_sync()
{
    QString url=BASE_URL + _detail;
    provider->fetch(url);
}

void FetchView::on_fetchView_doubleClicked(const QModelIndex &index)
{
    if(index.isValid())
    {
        QString label=index.data().toString();
        QString detail=fetchDetails.value(label);
        if(detail.isEmpty())
            return;

        ui->status->setText(detail);
        qApp->clipboard()->setText(detail);
    }
}
